#!/usr/bin/env python3

import os, urllib, json, sys, urllib.request
from gi.repository import Gtk, Gdk

text = sys.stdin.read()

lang = os.getenv('GEDIT_CURRENT_DOCUMENT_LANGUAGE')
if lang is None:
    lang = "text"

url_params = urllib.parse.urlencode({'paste_data': text, 'paste_lang': lang, 'mode':'json', 'api_submit':'true'})
openfpaste = urllib.request.urlopen("http://fpaste.org", bytes(url_params, 'utf-8')).read().decode("utf-8")
if openfpaste is None:
    print("Failed to send fpaste request.")

final_data = json.loads(openfpaste)

paste_url = "http://fpaste.org/" + final_data['result']['id']

disp = Gdk.Display.get_default()
clipboard = Gtk.Clipboard.get_for_display(disp, Gdk.SELECTION_CLIPBOARD)
clipboard.set_text(paste_url, len(paste_url))
clipboard.store()

print(paste_url + " has been copied to the clipboard.")
